import React, { Component } from 'react';
import { connect } from 'dva';
import { Form, Button, Card } from 'antd';
import BraftEditor from 'braft-editor';
import BraftEditorItem from '@/components/FormItems/BraftEditorItem';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

@connect()
@Form.create()
class BraftEditorDemo extends Component {
  componentDidMount() {
    const {
      form: { setFieldsValue },
    } = this.props;
    // 异步设置编辑器内容
    setTimeout(() => {
      setFieldsValue({
        content: BraftEditor.createEditorState('<p>Hello <b>World!</b></p>'),
      });
    }, 1000);
  }

  handleSubmit = e => {
    e.preventDefault();
    const {
      form: { validateFieldsAndScroll },
    } = this.props;
    validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log(values.content.toHTML());
      }
    });
  };

  render() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 },
      },
    };
    const extra = (
      <Button type="primary" htmlType="submit" onClick={this.handleSubmit}>
        提交
      </Button>
    );
    return (
      <PageHeaderWrapper extraContent={extra}>
        <Card>
          <Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
            <Form.Item {...formItemLayout} label="文章内容">
              {getFieldDecorator('content')(
                <BraftEditorItem
                  uploadApi="fileUploadUrl"
                  downloadApi="fileDownUrl"
                  idField="imageId"
                  placeholder="请输入文章内容"
                />
              )}
            </Form.Item>
          </Form>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default BraftEditorDemo;
